const express = require('express')
const router = express.Router()
const Topic = require('../../model/Topic')
const News = require('../../model/News')
const Comment = require('../../model/Comment')


//添加主题
router.post('/add', (req, res) => {
  new Topic(req.body).save().then(topic => {
    res.json(topic)
  })
})

// 查询全部主题
router.get('/', (req, res) => {
  const topic = Topic.find().then(topic => {
    return topic
  })
  const news = News.find().then(news => {
    return news
  })
  Promise.all([topic, news]).then(result => {
    let topic_info = []
    result[0].forEach(topic => {
      let obj = {}
      let arr = []
      result[1].forEach(news => {
        if (news.topic === topic.topic) {
          arr.push(news)
        }
      })
      obj.topic = topic.topic
      obj.news = arr
      topic_info.push(obj)
    })
    res.json(topic_info)
  })
})

// 删除主题
router.delete('/delete/:topic', (req, res) => {
  const topic = Topic.findOneAndRemove({
    topic: req.params.topic
  }).then(topic => '删除成功')
    .catch(err => '删除失败')
  const news = News.remove({
    topic: req.params.topic
  }).then(news => '删除成功')
    .catch(err => '删除失败')
  const comment = Comment.remove({
    topic: req.params.topic
  }).then(news => '删除成功')
    .catch(err => '删除失败')
  Promise.all([topic, news, comment])
    .then(result => res.json('删除成功'))
    .catch(err => res.status(400).json('删除失败'))
})


module.exports = router